package api

import (
	"cap/dao"
	"cap/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"github.com/sirupsen/logrus"
	"lib/http"
	"lib/id"
	"lib/structs/cap"
	"lib/structs/tables"
	"lib/utils"
	"time"
)

var ClientApi = new(clientApi)

type clientApi struct {
}

func (a clientApi) Register(c *gin.Context) {
	var in cap.RegisterInfo
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	m, err := dao.HostDao.FindByUid(in.Uid)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	if m.Id == 0 {
		metaMap := make(map[string]interface{})
		metaMap["api"] = in.Api
		m = tables.CapHost{
			Id:           id.GetSnowId(),
			Uid:          in.Uid,
			Ip:           in.Ip,
			GuaPort:      in.GuaPort,
			Status:       in.Status,
			GuaProtocol:  in.GuaProtocol,
			ClusterId:    0,
			BindUserID:   0,
			LockedUserID: 0,
			Meta:         utils.Obj2Str(metaMap),
			CreatedAt:    time.Now().Unix(),
		}
		err = dao.HostDao.Create(m)
		if err != nil {
			http.BadWithErr(c, err)
			return
		}
	} else {
		metaMap := make(map[string]interface{})
		metaMap["api"] = in.Api
		m.Ip = in.Ip
		m.GuaPort = in.GuaPort
		m.Status = in.Status
		m.Meta = utils.Obj2Str(metaMap)
		err = dao.HostDao.UpdateById(m)
		if err != nil {
			http.BadWithErr(c, err)
			return
		}
	}
	http.Ok(c, fmt.Sprintf("%d", m.Id))
}

func (a clientApi) UploadCloudApp(c *gin.Context) {
	in := struct {
		AppList []cap.AppInfo `json:"appList"`
		HostId  int64         `json:"hostId,string"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	apps := make([]tables.CapAppCollect, len(in.AppList))
	for i, item := range in.AppList {
		var ai = new(tables.CapAppCollect)
		_ = copier.Copy(ai, item)
		ai.HostId = in.HostId
		ai.Id = id.GetSnowId()
		apps[i] = *ai
	}
	err := dao.HostDao.BatchInsertAppCollectList(apps)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}

func (a clientApi) NoticeWinSessionChange(c *gin.Context) {
	in := struct {
		Msg    cap.WinSessionChangeMsg `json:"msg"`
		HostId int64                   `json:"hostId,string"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := service.SessionSer.HandeSessionChange(in.Msg, in.HostId)
	if err != nil {
		logrus.Errorf("handeSessionChange err: %v", err)
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}
